package masterserver;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import shared.*;

public class LogManager
{

    private ObjectOutputStream logWriter = null;
    private long logFileName = 0;

    public LogManager(long millis)
    {
	this.logFileName = millis;
	try
	{
	    System.out.println("Successfully initialized LogManager.");
	    String filename = Constants.MASTERSERVER_LOG_DIR + logFileName;
	    if (!Files.exists(Paths.get(filename)))
		Files.createFile(Paths.get(filename));
	    
	    BufferedOutputStream output = new BufferedOutputStream(
		    new FileOutputStream(filename, true));
	    this.logWriter = new ObjectOutputStream(output);

	} catch (IOException e)
	{
	    e.printStackTrace();
	}
    };

    public void addEntry(LogEntry entry)
    {
	try
	{
	    this.logWriter.writeObject(entry);
	    this.logWriter.flush();
	} catch (Exception e)
	{	   
	    // do nothing
	}
    }
    
    public void changeLogFile(long fileName)
    {
	try
	{
	    this.logWriter.close();
	} catch (IOException e)
	{
	    e.printStackTrace();
	}
	
	this.logFileName = fileName;
	
	try
	{
	    String filename = Constants.MASTERSERVER_LOG_DIR + logFileName;
	    if (!Files.exists(Paths.get(filename)))
		Files.createFile(Paths.get(filename));
	    
	    BufferedOutputStream output = new BufferedOutputStream(
		    new FileOutputStream(filename, true));
	    this.logWriter = new ObjectOutputStream(output);
	    

	} catch (IOException e)
	{
	    e.printStackTrace();
	}
		
    }
    
    
    public String getLatestLogFileName()
    {
	return Constants.MASTERSERVER_LOG_DIR + logFileName;
    }

}
